#define _CRT_SECURE_NO_WARNINGS
#include"SList.h"
void SLTPrint(SLTNode* phead)
{
	SLTNode* pcur = phead;
	while (pcur)
	{
		printf("%d ->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}
SLTNode* SLTBuyNode(SLtDataType x)
{
	SLTNode* tmp = (SLTNode*)malloc(sizeof(SLTNode));
	if (tmp == NULL)
	{
		perror("malloc fail");
		exit(1);
	}
	tmp->data = x;
	tmp->next = NULL;
	return tmp;
}
void SLTPushBack(SLTNode** pphead, SLtDataType x)
{
	assert(pphead);
	SLTNode* newNode = SLTBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = newNode;
	}
	else
	{
		SLTNode* ptail = *pphead;
		while (ptail->next)
		{
			ptail = ptail->next;
		}
		ptail->next = newNode;
	}
}
void SLTPushFront(SLTNode** pphead, SLtDataType x)
{
	assert(pphead);
	SLTNode* newNode = SLTBuyNode(x);
	newNode->next = *pphead;
	*pphead = newNode;
	
}
void SLTPopBack(SLTNode** pphead)
{
	assert(pphead && *pphead);
	
	
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* ptail = *pphead;
		SLTNode* prev = *pphead;
		while (ptail->next)
		{
			prev = ptail;
			ptail = ptail->next;
		}
		prev->next = NULL;
		free(ptail);
		ptail = NULL;

	}
	
}
void SLTPopFront(SLTNode** pphead)
{
	assert(pphead && *pphead);
		SLTNode* prev = *pphead;
		*pphead = (*pphead)->next;
		free(prev);
		prev = NULL;

}
SLTNode* SLTFind(SLTNode* phead, SLtDataType x)
{
	assert(phead);
	SLTNode* pcur = phead;
	while (pcur)
	{
		if (pcur->data == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLtDataType x)
{
	assert(pphead && pos);
	if (*pphead == pos)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		SLTNode* newNode = SLTBuyNode(x);
		newNode->next = pos;
		prev->next = newNode;
	}

}
void SLTInsertAfter( SLTNode* pos, SLtDataType x)
{
	assert(pos);
	SLTNode* newNode = SLTBuyNode(x);
	newNode->next = pos->next;
	pos->next = newNode;
}
void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead && pos && *pphead);
	if (*pphead == pos)
	{
		SLTPopFront(pphead);
	}
	else
	{
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
void SLTEraseAfter(SLTNode* pos)
{
	assert(pos&&pos->next);
	SLTNode* next = pos->next;
	pos->next = next->next;
	free(next);
	next = NULL;

}
void SLTDestroy(SLTNode** pphead)
{
	assert(pphead);
	SLTNode* prev = *pphead;
	while (*pphead)
	{
		prev = *pphead;
		*pphead = (*pphead)->next;
		free(prev);
	}
	free(*pphead);
	*pphead = NULL;


}